package com.abocode.aichat.core.application;

import com.abocode.aichat.core.application.impl.UserValidatorService;
import com.abocode.aichat.data.*;
import com.abocode.aichat.server.context.channel.ChannelWrapper;
import com.abocode.aichat.server.context.ServerRuntimeContext;
import com.abocode.aichat.server.modules.ModuleServiceHandler;
import com.abocode.aichat.server.context.delivery.reply.Replies;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author guanxf
 */
@Service("authHandler")
public class AuthHandler implements ModuleServiceHandler {
    @Autowired
    private UserValidatorService userValidatorService;
    @Override
    public Replies execute(ChannelWrapper channelWrapper, MessageStanza stanza, ServerRuntimeContext serverRuntimeContext) {
        if(userValidatorService ==null){
            throw new RuntimeException("IUserValidate is not found");
        }
        ReqMessageBody body = JSON.parseObject(stanza.body().toString(),ReqMessageBody.class);
        boolean flag= userValidatorService.validate(body);
        if (flag) {
            EntityImpl entity = userValidatorService.entity(body);
            serverRuntimeContext.getProtocolChannelRegistry().registerEntity(channelWrapper.getChannel(), entity);
            Replies replies = new Replies();
            RespMessage map = new RespMessage();
            map.setCode(200);
            map.setMessage("");
            map.setData(entity.getFullName());
            MessageStanza messageStanza = StanzaWrapper.wrapper(stanza, map);
            replies.addReply(channelWrapper.getChannel(), messageStanza);
            return replies;
        }else{
            throw new RuntimeException("validate error");
        }
    }

    @Override
    public ModuleServiceType moduleServiceType() {
        return ModuleServiceType.auth;
    }
}
